﻿using System;
using System.Collections.Generic; 
using System.Text;
using System.ComponentModel;
using System.Web.UI;
using System.Web.UI.WebControls;

[assembly: System.Web.UI.WebResource("Runda.EShop.Common.Component.IntegerTextBox.Resources.IntegerTextBox.js", "application/x-javascript", PerformSubstitution = true)]
namespace Runda.EShop.Common.Component
{
    [DefaultProperty("Text")]
    [ControlValueProperty("Value")]
    [ToolboxData("<{0}:IntegerTextBox runat=server></{0}:IntegerTextBox>")]
    public class IntegerTextBox : TextBox
    {
        public string ControlName
        {
            get
            {
                return this.GetType().Name;
            }
        }

        public int? Value
        {
            get
            {
                if (this.Text.Length == 0)
                {
                    return null;
                }

                return Convert.ToInt32(this.Text);
            }
            set
            {
                if (value != null)
                {
                    this.Text = value.ToString();
                }
                else
                {
                    this.Text = string.Empty;
                }
            }
        }


        public bool EnableNegative
        {
            get
            {
                object value = this.ViewState["EnableNegative"];
                if (value == null)
                {
                    return false;
                }

                return (bool)value;
            }
            set
            {
                this.ViewState["EnableNegative"] = value;
            }
        }

        #region Event

        /// <summary>
        /// OnInit
        /// </summary>
        /// <param name="e"></param>
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            if (this.EnableNegative)
            {
                this.MaxLength = 8;
            }
            else
            {
                this.MaxLength = 7;
            }
            this.CssClass = "defaultIntegerTextBox";
            this.Page.ClientScript.RegisterClientScriptResource(this.GetType(), "Runda.EShop.Common.Component.IntegerTextBox.Resources.IntegerTextBox.js");
        }

        /// <summary>
        /// 添加控件的Attributes
        /// </summary>
        /// <param name="writer"></param>
        protected override void AddAttributesToRender(HtmlTextWriter writer)
        {
            writer.AddAttribute("data-control", "IntegerTextBox");

            writer.AddAttribute("data-enable-negative", this.EnableNegative.ToString().ToLower());

            // 关闭IME
            this.Attributes["Style"] = "ime-mode:Disabled;";

            base.AddAttributesToRender(writer);
        }

        #endregion
    }
}
